<script setup>
import { ref, onMounted, computed } from 'vue'
import { submitUserInfoService, getUserInfoService } from '@/apis/center'
import { useUserStore } from '@/stores/user'
import { Avatar } from '@element-plus/icons-vue'
const UserStore = useUserStore()

// 获取表单
const formRef = ref(null)

// 用户个人信息
const formModel = ref({
  avatar: '',
  phone: '',
  email: ''
})

// 用户名和用户ID存入表单
const username = UserStore.UserList.username
formModel.value.id = UserStore.UserList.id

const rules = {
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    {
      pattern:
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
      message: '请输入正确的邮箱',
      trigger: 'blur'
    }
  ]
}

// 获取用户个人信息
const getUserInfo = async () => {
  const res = await getUserInfoService(formModel.value.id)
  formModel.value = res.data.data
}

// 提交用户个人信息
const submitUserInfo = async () => {
  await formRef.value.validate()
  // 提交用户个人信息
  await submitUserInfoService(formModel.value)
  ElMessage.success('保存成功！')
  UserStore.UserList.avatar = formModel.value.avatar
  getUserInfo()
}

onMounted(() => {
  getUserInfo()
})

// 上传用户头像
// 头像上传路径URL
const uploadUrl = computed(() => {
  return `http://127.0.0.1:3000/user/avatar/upload`
})

// 图片上传前添加请求头
const token = computed(() => UserStore.UserList.token)
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${token.value}`
}))

// 图片上传前的操作
const beforeAvatarUpload = () => {
  if (!token.value) {
    ElMessage.error('请先登录或获取token')
    return false
  }
  return true
}

// 图片上传成功时的操作
const handleAvatarSuccess = async (response) => {
  formModel.value.avatar = response.url
  ElMessage.success('头像上传成功')
}
// 图片上传失败时的操作
const handleAvatarError = (error) => {
  ElMessage.error('头像上传失败', error.message)
}
</script>

<template>
  <h2>个人资料</h2>
  <el-row :gutter="20" justify="flex-start">
    <el-col :offset="3">
      <el-form
        class="form"
        autocomplete="off"
        size="large"
        ref="formRef"
        label-width="200px"
        :rules="rules"
        :model="formModel"
      >
        <el-col :offset="4">
          <el-form-item>
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :before-upload="beforeAvatarUpload"
            >
              <template #default>
                <el-avatar
                  style="width: 100px; height: 100px"
                  :src="formModel.avatar"
                >
                  <el-icon class="icon">
                    <Avatar></Avatar>
                  </el-icon>
                </el-avatar>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-form-item label="用户名">
          <el-input disabled v-model="username"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="formModel.phone"
            placeholder="请输入联系电话"
          ></el-input>
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input
            v-model="formModel.email"
            placeholder="请输入电子邮箱"
          ></el-input>
        </el-form-item>

        <el-col :offset="21">
          <el-button type="primary" @click="submitUserInfo">保存</el-button>
        </el-col>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.form {
  height: 650px;
  max-width: 600px;
  padding-top: 50px;
  .avatar-uploader {
    .icon {
      font-size: 45px;
    }
  }
}
</style>
